package cn.cvs.controller.sysUser;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.sysRole.SysRoleService;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger=Logger.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    //跳转到登录页面
    @RequestMapping(value = "/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.debug("登录方法");
        //调用service方法，进行用于匹配
        SysUser sysUser = sysUserService.selectByAccount(account);
        SysUser sysUser1=sysUserService.login(account,password);
        if (null==sysUser){
//            session.setAttribute(Constants.USER_SESSION,sysUser);
            //登录成功，重定向到/user/toMain接口
//            request.setAttribute("error","用户名不存在");
            throw new RuntimeException("用户名不存在");
//            return "login";
        }else if (sysUser1==null){
            //用户不存在，登录失败，跳转到登录页面
//            throw new RuntimeException("用户名或密码不正确");
//            request.setAttribute("error","密码输入错误");
            throw new RuntimeException("密码输入错误");
//            return "login";
        }else {
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "redirect:/user/toMain";
        }
    }
    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION)==null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    //捕获异常信息
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest req){
        req.setAttribute("error",e);
        return "login";
    }

    //一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password){
        SysUser user=sysUserService.login(account,password);
        if (null==user){
            //登录失败
            throw new RuntimeException("用户名或者密码不正确!");
        }
        return "redirect:/user/toMain";
    }

    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1") Integer pageIndex){
        List<SysUser> userList=null;
        try {
            //设置页面容量
            int pageSize= Constants.pageSize;
            //总数量（表）
            int totalCount=sysUserService.getUserCount(queryRealName,queryRoleId);
            //总页数
            PageSupport pages=new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount=pages.getTotalPageCount();
            //控制首页与尾页
            if (pageIndex>totalPageCount){
                pageIndex=totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList=sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            List<SysRole> roleList=null;
            roleList=sysRoleService.getRoleList();
            model.addAttribute("userList",userList);
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }


    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "redirect:/user/toLogin";
    }

    //跳转到添加用户页面
    @GetMapping("toAdd")
    public String toAdd(){
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件存储路径:" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("原文件名为:" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);
                logger.debug("原文件后缀名为:" + prefix);
                int filesize = 500000;
                logger.debug("文件大小:" + attach.getSize());
                if (attach.getSize() > filesize) {
                    //上传大小不得超过500kb
                    request.setAttribute("uploadFileError", "*上传大小不得超过500KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    //上次图片格式正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.debug("新文件名称为:" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("errorInfo", "*上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.debug("idPicPath" + idPicPath);
                    logger.debug("workPicPath" + workPicPath);
                } else {
                    request.setAttribute(errorInfo, "*上传图片格式不正确");
                    flag = false;
                }
            }
        }

        if (flag) {
            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            sysUser.setCreatedTime(new Date());
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            if (sysUserService.add(sysUser)) {
                return "redirect:/user/list";
            }
        }
        return "sysUser/add";
    }
        //判断文件是否为空
//        if (!idPic.isEmpty()){
//            String path=request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfiles");
//            logger.info("上传文件路径"+path);
//            String originalFile=idPic.getOriginalFilename();//原文件名
//            logger.info("原文件名为:"+originalFile);
//            String prefix= FilenameUtils.getExtension(originalFile);
//            logger.info("原文件后缀名为:"+prefix);
//            int filesize=500000;
//            logger.debug("文件大小:"+idPic.getSize());
//            if (idPic.getSize()>filesize){
//                //上传大小不得超过500kb
//                request.setAttribute("uploadFileError","*上传大小不得超过500KB");
//                return "sysUser/add";
//            }else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")){
//                //上次图片格式正确
//                String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal."+prefix;
//                logger.debug("新生成的文件名称为:"+fileName);
//                File targetFile=new File(path);
//                if (!targetFile.exists()){
//                    targetFile.mkdirs();
//                }
//                //保存
//                try {
//                    idPic.transferTo(new File(targetFile,fileName));
//                }catch (Exception e){
//                    e.printStackTrace();
//                    request.setAttribute("uploadFileError","*上传失败！");
//                    return "sysUser/add";
//                }
//                idPicPath=File.separator+"statis"+File.separator+"uploadfiles"+File.separator+fileName;
//            }else {
//                request.setAttribute("uploadFileError","*上次图片格式不正确");
//                return "sysUser/add";
//            }
//        }
//        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
//        sysUser.setIdPicPath(idPicPath);
//        if (sysUserService.add(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }

//    @GetMapping("/view/{id}")
//    public String view(@PathVariable Integer id,Model model){
//        logger.debug("根据用户查询");
//        SysUser sysUser = sysUserService.getUserById(id);
//        model.addAttribute(sysUser);
//        return "sysUser/view";
//    }

    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam Integer uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser=sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }

    //修改用户信息
    @PostMapping("/update")
    public String update(SysUser sysUser,HttpSession session){
        logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.update(sysUser)){
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }
//    private ArrayList<SysUser> sysUserList=new ArrayList<SysUser>();
//
//    //用于返回查询到的用户数据
//    private ArrayList<SysUser> queryUserList=new ArrayList<SysUser>();
//    public SysUserController(){
//        try {
//            sysUserList.add(new SysUser(5,"zhaojing","赵静","5555555",1,"13054784445","上海市宝山区",1,1,new Date(),1,new Date()));
//            sysUserList.add(new SysUser(4,"wanglin","王林","4444444",1,"18965652364","北京市学院路",1,1,new Date(),1,new Date()));
//            sysUserList.add(new SysUser(1,"test001","测试用户001","1111111",1,"13566669998","北京市朝阳区",1,1,new Date(),1,new Date()));
//            sysUserList.add(new SysUser(2,"zhaoyan","赵燕","2222222",1,"18678786545","北京市海淀区",1,1,new Date(),1,new Date()));
//            sysUserList.add(new SysUser(3,"wanglin","test003","1111111",1,"13121334531","北京市海淀区",1,1,new Date(),1,new Date()));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
//
//    //查询所有用户
//    @GetMapping("/list")
//    public String list(Model model){
//        logger.info("当查询条件为空时，查询用户信息");
//        queryUserList.clear();
//        queryUserList.addAll(sysUserList);
//        model.addAttribute("queryUserList",queryUserList);
//        return "sysUser/sysUserList";
//    }
//
//    //根据条件查询部分用户
//    @PostMapping("/list")
//    public String list(@RequestParam(value = "realName",required = false) String realName,Model model){
//        logger.info("查询条件:【realName】="+realName+",查询用户信息");
//        queryUserList.clear();
//        if (realName!=null &&!realName.equals("")){
//            for (SysUser user:sysUserList){
//                if (user.getRealName().indexOf(realName)!=-1){
//                    queryUserList.add(user);
//                }
//            }
//        }else {
//            queryUserList.addAll(sysUserList);
//        }
//        model.addAttribute("queryUserList",queryUserList);
//        return "sysUser/sysUserList";
//    }

    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account){
        logger.debug("验证用户名account="+account+"的用户是否存在");
        HashMap<String,Object> resultMap=new HashMap<String, Object>();
        if (StringUtils.isNullOrEmpty(account)){
            resultMap.put("exist",1);
        }else{
            SysUser sysUser=sysUserService.selectByAccount(account);
            if (null!=sysUser){
                resultMap.put("exist",1);
            }else{
                resultMap.put("exist",0);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @GetMapping("/{id}/view")
    public Object view(@PathVariable String id) {
        logger.debug("根据id查询用户详细id:" + id);
        SysUser sysUser = null;
        try {
            sysUser = sysUserService.getUserById(Integer.valueOf(id));
            logger.debug("查询到用户信息：" + sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        return sysUser;
    }

    @RequestMapping(value = "toUpdatePwd")
    public String toUpdatePwd(){
        return "sysUser/updatePassword";
    }

    @ResponseBody
    @PostMapping(value = "checkOldPwd")
    public Object checkOldPwd(String oldPassword,HttpSession session){
        HashMap<String,Object> map = new HashMap<>();
        if(oldPassword == null || "".equals(oldPassword)){
            map.put("result","error");
        }else{
            SysUser sysUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
            if(sysUser == null){
                map.put("result","sessionerror");
            }else{
                if(sysUser.getPassword().equals(oldPassword)){
                    map.put("result","true");
                }else{
                    map.put("result","false");
                }
            }
        }
        return map;
    }

    @PostMapping("/savePassword")
    public String savePassword(@RequestParam Integer id,@RequestParam String rnewpassword){
        SysUser sysUser=new SysUser();
        sysUser.setPassword(rnewpassword);
        sysUser.setId(id);
        int result= sysUserService.updatePwd(sysUser);
        if (result>0){
            return "redirect:/user/toLogin";
        }
        return "redirect:/user/toUpdatePwd";
    }
}
